/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * VisualizaAnexos.java
 *
 * Created on 19/09/2010, 21:42:41
 */

package view.execucao;

import Util.FabricaConexoes;
import Util.manipulaConexao;
import com.mysql.jdbc.util.ResultSetUtil;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author Administrador
 */
public class VisualizaAnexos extends javax.swing.JDialog {

    /** Creates new form VisualizaAnexos */
    public VisualizaAnexos(java.awt.Frame parent, boolean modal, int idtarefa) {
        super(parent, modal);
        initComponents();

        String sql = "Select id,nome from tb_documento_tarefa where id_tarefa = "+ idtarefa + ";" ;
        manipulaConexao.preenchetable(jTable1, sql);

        jTable1.getSelectionModel().addListSelectionListener(selectionListener);
        jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        //pane.add(desc);

        //Cria a reorganização da tabela através do clique na coluna
        jTable1.setAutoCreateRowSorter(true);
        TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(jTable1.getModel());
        jTable1.setRowSorter(sorter);

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jFileChooser1 = new javax.swing.JFileChooser();
        jPanel1 = new javax.swing.JPanel();
        jbt_salvar = new javax.swing.JButton();
        jbt_excluir = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();

        jFileChooser1.setApproveButtonText("Salvar");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Anexos");

        jbt_salvar.setText("Salvar");
        jbt_salvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbt_salvarActionPerformed(evt);
            }
        });
        jPanel1.add(jbt_salvar);

        jbt_excluir.setText("Excluir");
        jPanel1.add(jbt_excluir);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jLabel1.setText("Documentos anexados à tarefa:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                    .addComponent(jLabel1)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 263, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(12, 12, 12))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-416)/2, (screenSize.height-375)/2, 416, 375);
    }// </editor-fold>//GEN-END:initComponents

    private void jbt_salvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbt_salvarActionPerformed

         final JFileChooser fc = new JFileChooser();
        int res = fc.showSaveDialog(null);
        fc.setFileSelectionMode(fc.DIRECTORIES_ONLY);
        if(res == JFileChooser.APPROVE_OPTION)
        {
          String nome = fc.getSelectedFile().getName();
          String diretorio = fc.getCurrentDirectory().getPath();
          
          String salvar;          


                
                Blob blob = null;
                InputStream bin = null;
                FileOutputStream bout = null;
                byte[] bbuf = new byte[1024];
                int bytesRead = 0;

                try{
                     PreparedStatement stm;
                     ResultSet rs;
                     ResultSetUtil rs2;




                        String sql = "Select * from tb_documento_tarefa where id = " + id + ";";
                        if(!FabricaConexoes.verificaConexao()) FabricaConexoes.getConexao();
                        stm = FabricaConexoes.returnStatement(sql);
                        rs = FabricaConexoes.returnResult(stm);
                        while(rs.next()){

                            blob = rs.getBlob("documento");

                           if(nome.compareToIgnoreCase("") == 0)      salvar = diretorio.concat("\\" + rs.getString("nome"));
                           else salvar = diretorio.concat("\\" + nome); 

                            JOptionPane.showMessageDialog(null, "Arquivo gravado com sucesso!");
                            bin = blob.getBinaryStream();
                            bout = new FileOutputStream(salvar);

                            while ((bytesRead = bin.read(bbuf)) != -1) {
                                 bout.write(bbuf, 0, bytesRead);
                            }
                        }

                        
                        blob.free();
                        bin.close();
                        bout.close();

                    }catch(Exception e){
                        e.printStackTrace();
                    }

                    dispose();
        }else{
            dispose();
        }


    }//GEN-LAST:event_jbt_salvarActionPerformed

    private ListSelectionListener selectionListener = new ListSelectionListener()
    {
        public void valueChanged(ListSelectionEvent e)
        {
            try{

            int linha = jTable1.getSelectedRow();
            if(linha == -1)
            {
                //JOptionPane.showMessageDialog(null, "Não há tarefa selecionada, verifique!");
                return;
            }
            id =  Integer.valueOf(String.valueOf(jTable1.getValueAt(linha,0)));
            if(id != 0)
            {


            }
            //String desc = String.valueOf(jtbtarefas.getValueAt(linha, 2));
            //jtbtarefas.setToolTipText(desc);
        }catch(Exception exc)
        {
            JOptionPane.showMessageDialog(null, exc.getMessage(),"Erro desconhecido",0);
        }

        }


    };


    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                VisualizaAnexos dialog = new VisualizaAnexos(new javax.swing.JFrame(), true, 0);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JButton jbt_excluir;
    private javax.swing.JButton jbt_salvar;
    // End of variables declaration//GEN-END:variables
    private int id;
}
